<?php

namespace app\command;

use app\crm\model\ShopPersonAchievementModel;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use Workerman\Crontab\Crontab;
use Workerman\Worker;
class ShopPersonStatistics extends Command
{
    /**
     * @var int
     */
    protected $timer;
    /**
     * @var int|float
     */
    protected $interval = 2;
    protected function configure()
    {
        // 指令配置
        $this->setName('timer')
            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d', null, Option::VALUE_NONE, 'daemon（守护进程）方式启动')
            ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次')
            ->setDescription('开启/关闭/重启 定时任务');
    }
    protected function init(Input $input, Output $output)
    {
        global $argv;
        if ($input->hasOption('i'))
            $this->interval = floatval($input->getOption('i'));
        $argv[1] = $input->getArgument('status') ?: 'start';
        if ($input->hasOption('d')) {
            $argv[2] = '-d';
        } else {
            unset($argv[2]);
        }
    }
    protected function execute(Input $input, Output $output)
    {
        $this->init($input, $output);
        //创建定时器任务
        $task = new Worker();
        $task->count = 1;
        $task->name = "员工业绩";
        $task->onWorkerStart = [$this, 'start'];
        $task->runAll();
    }
    public function stop()
    {
        //手动暂停定时器
        \Workerman\Lib\Timer::del($this->timer);
    }
    public function start()
    {
        new Crontab('0 30 1 * * *', function(){
            $this->setShopPersonStatistics();
        });
//        $this->setShopPersonStatistics();

    }
    public function setShopPersonStatistics($shopIds = [])
    {
        $start_time = strtotime(date('Y-m-1',strtotime('-1 month')));
//        $start_time = strtotime(date('Y-m-1'));

        $end_time = strtotime(date('Y-m-t'));
        $mid_time = strtotime(date('Y-m-t',strtotime('-1 month')));
        $now = $start_time;
        $idS = Db::name('shop_person')
            ->where('status','<>',3)
            ->column('id');
//        $shopIds=['78214928701306'];
        if(!empty($shopIds))
        {
            $idS = Db::name('shop_person')
                ->where('status','<>',3)
                ->where('shop_id','in',$shopIds)
                ->column('id');
        }
        $achievement = new ShopPersonAchievementModel();
        $where = [];
        array_push($where,['time','=',$start_time]);
        array_push($where,['person_id','in',$idS]);
        $result = ShopPersonAchievementModel::where($where)->select()->toArray();
        $data = [];
        foreach ($result as $key =>$value)
        {
            $data[$value['person_id']][$value['type']]=$value;
        }
        while ($now<=$mid_time)
        {
            $this->getDayAdminShopPersonStatistics($idS,$data,$now,$now+24*60*60-1,$start_time);

            $now+=24*60*60;
        }
        $this->getDayAdminShopPersonStatistics($idS,$data,$start_time,$mid_time+24*60*60-1,$start_time,1);


        $where = [];
        array_push($where,['time','=',$mid_time+24*60*60]);
        array_push($where,['person_id','in',$idS]);
        $result = ShopPersonAchievementModel::where($where)->select()->toArray();
        $data2 = [];
        foreach ($result as $key =>$value)
        {
            $data2[$value['person_id']][$value['type']]=$value;
        }
        while ($now<=$end_time)
        {
            $this->getDayAdminShopPersonStatistics($idS,$data2,$now,$now+24*60*60-1,$mid_time+24*60*60);
            $now+=24*60*60;
        }
        $this->getDayAdminShopPersonStatistics($idS,$data2,$mid_time+24*60*60,$end_time+24*60*60-1,$mid_time+24*60*60,1);
        $insertData = [];
        foreach ($data as $value)
        {
            foreach ($value as $v)
            {
                array_push($insertData,$v);
            }
        }
        foreach ($data2 as $value)
        {
            foreach ($value as $v)
            {
                array_push($insertData,$v);
            }
        }
        $achievement->saveAll($insertData);
        print_r("完了".PHP_EOL);


        return true;

    }
    public function getDayAdminShopPersonStatistics($idS,&$data,$start_time,$end_time,$month,$is_sum=0)
    {
        print_r(date('Y-m-d',$start_time).PHP_EOL);
        $day = 'd'.date('d',$start_time);
        if($is_sum==1)
        {
            $day="sum";
        }
        $where = [];
        array_push($where,['create_time','>=',$start_time]);
        array_push($where,['create_time','<=',$end_time]);

        $serviceOneNum = Db::name('service_log')->where($where)->where('nurse_id_one','in',$idS)->group('nurse_id_one')->column('count(*)','nurse_id_one');
        $serviceTwoNum = Db::name('service_log')->where($where)->where('nurse_id_two','in',$idS)->group('nurse_id_two')->column('count(*)','nurse_id_two');

        $outreachNum = Db::name('customer')->where('operator','in',$idS)->where(function ($query)use($start_time,$end_time){
            $query->whereOr([
                ['first_time','between',[$start_time,$end_time]],
                ['second_time','between',[$start_time,$end_time]]
            ]);
        })->group('operator')->column('count(*)','operator');

        $where = [];
        array_push($where,['order_type','=',1]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $newOrderReal = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(pay_amount)','sale_id');
        $where = [];
        array_push($where,['order_type','=',1]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $newOrderRefund = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(total_amount)','sale_id');

        $where = [];
        array_push($where,['order_type','=',2]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $repairOrderReal = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(pay_amount)','sale_id');
        $where = [];
        array_push($where,['order_type','=',2]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $repairOrderRefund = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(total_amount)','sale_id');

        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['is_outreach','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $outreachReal = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(pay_amount)','sale_id');
        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['is_outreach','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $outreachRefund = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(pay_amount)','sale_id');

        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['is_introduction','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $introductionReal = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(pay_amount)','sale_id');
        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['is_introduction','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['sale_id','in',$idS]);
        $introductionRefund = Db::name('shop_refund_order')->where($where)->group('sale_id')->column('sum(pay_amount)','sale_id');

        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['is_experience','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['experience_id','in',$idS]);
        $experienceReal = Db::name('shop_refund_order')->where($where)->group('experience_id')->column('sum(pay_amount)','experience_id');
        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['is_experience','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['experience_id','in',$idS]);
        $experienceRefund = Db::name('shop_refund_order')->where($where)->group('experience_id')->column('sum(pay_amount)','experience_id');
        $result = [];
        foreach ($idS as $key =>$value)
        {
            $temp['serviceNum']=$serviceOneNum[$value]??0;
            if(!empty($serviceTwoNum[$value]))
            {
                $temp['serviceNum']+=$serviceTwoNum[$value];
            }
            $temp['outreachNum']=$outreachNum[$value]??0;
            $temp['newOrderReal']=$newOrderReal[$value]??0;
            if(!empty($newOrderRefund[$value]))
            {
                $temp['newOrderReal']-=$newOrderRefund[$value];
            }
            $temp['repairOrderReal']=$repairOrderReal[$value]??0;
            if(!empty($repairOrderRefund[$value]))
            {
                $temp['repairOrderReal']-=$repairOrderRefund[$value];
            }
            $temp['outreachReal']=$outreachReal[$value]??0;
            if(!empty($outreachRefund[$value]))
            {
                $temp['outreachReal']-=$outreachRefund[$value];
            }
            $temp['introductionReal']=$introductionReal[$value]??0;
            if(!empty($introductionRefund[$value]))
            {
                $temp['introductionReal']-=$introductionRefund[$value];
            }
            $temp['experienceReal']=$experienceReal[$value]??0;
            if(!empty($experienceRefund[$value]))
            {
                $temp['experienceReal']-=$experienceRefund[$value];
            }
            if(empty($data[$value]['serviceNum']))
            {
                $data[$value]['serviceNum']=[
                    'person_id'=>$value,
                    'type'=>'serviceNum',
                    'time'=>$month,
                    $day=>$temp['serviceNum']
                ];
            }else{
                $data[$value]['serviceNum'][$day]=$temp['serviceNum'];
            }
            if(empty($data[$value]['outreachNum']))
            {
                $data[$value]['outreachNum']=[
                    'person_id'=>$value,
                    'type'=>'outreachNum',
                    'time'=>$month,
                    $day=>$temp['outreachNum']
                ];
            }else{
                $data[$value]['outreachNum'][$day]=$temp['outreachNum'];
            }
            if(empty($data[$value]['newOrderReal']))
            {
                $data[$value]['newOrderReal']=[
                    'person_id'=>$value,
                    'type'=>'newOrderReal',
                    'time'=>$month,
                    $day=>$temp['newOrderReal']
                ];
            }else{
                $data[$value]['newOrderReal'][$day]=$temp['newOrderReal'];
            }
            if(empty($data[$value]['repairOrderReal']))
            {
                $data[$value]['repairOrderReal']=[
                    'person_id'=>$value,
                    'type'=>'repairOrderReal',
                    'time'=>$month,
                    $day=>$temp['repairOrderReal']
                ];
            }else{
                $data[$value]['repairOrderReal'][$day]=$temp['repairOrderReal'];
            }
            if(empty($data[$value]['outreachReal']))
            {
                $data[$value]['outreachReal']=[
                    'person_id'=>$value,
                    'type'=>'outreachReal',
                    'time'=>$month,
                    $day=>$temp['outreachReal']
                ];
            }else{
                $data[$value]['outreachReal'][$day]=$temp['outreachReal'];
            }
            if(empty($data[$value]['introductionReal']))
            {
                $data[$value]['introductionReal']=[
                    'person_id'=>$value,
                    'type'=>'introductionReal',
                    'time'=>$month,
                    $day=>$temp['introductionReal']
                ];
            }else{
                $data[$value]['introductionReal'][$day]=$temp['introductionReal'];
            }
            if(empty($data[$value]['experienceReal']))
            {
                $data[$value]['experienceReal']=[
                    'person_id'=>$value,
                    'type'=>'experienceReal',
                    'time'=>$month,
                    $day=>$temp['experienceReal']
                ];
            }else{
                $data[$value]['experienceReal'][$day]=$temp['experienceReal'];
            }
        }
    }
}
